import { ChangeDetectionStrategy, Component, OnInit, Pipe, PipeTransform, ViewChild } from '@angular/core';
import { filter, map, uniqueId } from 'lodash';
import { DatatableComponent } from '@iux/live';

interface DemoUser {
  id: string;
  name: string;
  age: number;
  expand: boolean;
  random: number;
  disabled: boolean;
}

@Pipe({ name: 'userProp' })
export class UserPropPipe implements PipeTransform {
  transform(value: DemoUser[], exponent: string = 'name') {
    return map(value, item => item[exponent]).join(',');
  }
}

@Pipe({ name: 'selectable' })
export class SelectionPipe implements PipeTransform {
  transform(value: DemoUser[], exponent: string = 'disabled') {
    return filter(value, item => !item[exponent]);
  }
}

@Component({
  selector: 'app-checkbox-selection',
  templateUrl: './checkbox-selection.component.html',
  styles: [
    `
      section {
        margin-bottom: 16px;
      }
      section button:not(:last-child) {
        margin-right: 16px;
      }
      lv-paginator {
        margin-top: 16px;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CheckboxSelectionComponent implements OnInit {
  data: DemoUser[];
  selection: DemoUser[];
  @ViewChild(DatatableComponent, { static: false }) lvTable: DatatableComponent;
  constructor() {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.data = Array.from({ length: 400 }).map((item, key) => this.initUser(key, key % 2 !== 0));
    // 直接赋值选中项
    this.selection = [this.data[0], this.data[2]];
  }

  updateData() {
    this.initData();
  }

  selectOdd() {
    // 方法一：调用方法赋值选中项
    this.lvTable.bulkSelection(this.data.filter((item, key) => !(key % 2)));
  }

  selectFifthRow() {
    // 方法二：更新selection
    this.selection = [this.data[4]];
  }

  clearSelection() {
    this.lvTable.clearSelection();
  }

  initUser(key: number, disabled: boolean) {
    return {
      id: uniqueId('uid'),
      name: `user${key}`,
      age: 10 + key,
      expand: false,
      random: parseInt(`${Math.random() * 100  }`, 10),
      disabled,
      checkboxTip: disabled ? '当前数据不可选择' : '',
    };
  }

  toggleSelect(source) {
    if (source.disabled) {
      return;
    }
    this.lvTable.toggleSelection(source);
  }

  checkAllChange(source) {
    console.log('check all:', source);
  }

  checkOneChange(source) {
    console.log('check one', source);
  }

  selectionChange(source) {
    console.log('selection change', source);
  }
}
